package com.tamartech.planning.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;

import com.tamartech.planning.data.Application;


public class ApplicationDAO extends DAO
{
   public Application save (Application a) 
         throws Exception
   {
      try
      {
         begin();
         getSession().save(a);
         commit();
         return a;
      }
      catch (HibernateException e)
      {
         rollback();
         throw new Exception("Could not create application", e);
      }
   }


   public void update(Application a) throws Exception 
   {
      try 
      {
         begin();
         getSession().update(a);
//         getSession().save(a);
         commit();
      } 
      catch (HibernateException e) 
      {
         rollback();
         throw new Exception("Could not update application", e);
      }
   }

   public Application get (Long id) throws Exception 
   {
      try 
      {
         begin();
         Application a = (Application) getSession().load(Application.class, id);
         commit();
         return a;
      } 
      catch (HibernateException e) 
      {
         rollback();
         throw new Exception("Could not obtain application " + id, e);
      }
   }
   
   public Application getByOpenlyLocalId (Long openlyLocalId) throws Exception 
   {
      try 
      {
         begin();
         Query q = getSession().createQuery("from Application where openlyLocalId = :openlyLocalId");
         q.setLong ("openlyLocalId", openlyLocalId);
         Application a = (Application) q.uniqueResult();
         commit();
         return a;
      } 
      catch (HibernateException e) 
      {
         rollback();
         return null;
      }
   }

   
   @SuppressWarnings("unchecked")
   public List<Application> list() throws Exception 
   {
      try 
      {
         begin();
         Query q = getSession().createQuery("from Application");
         List<Application> list = q.list();
         commit();
         return list;
      } 
      catch (HibernateException e) 
      {
         rollback();
         throw new Exception("Could not list the applications", e);
      }
   }

   
   public void delete(Application a)
      throws Exception
   {
      try
      {
         begin();
         getSession().delete(a);
         commit();
      }
      catch (HibernateException e)
      {
         rollback();
         throw new Exception("Could not delete application", e);
      }
   }
}
